package com.panda.web.utils.task;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.panda.web.configuration.CityConstants;
import com.panda.web.domain.dto.JobDTO;
import com.panda.web.domain.vo.JobVO;
import com.panda.web.domain.vo.commons.*;
import com.panda.web.entity.commons.SearchContent;
import com.panda.web.entity.py.Company;
import com.panda.web.entity.py.Job;
import com.panda.web.entity.wechat.WechatUser;
import com.panda.web.entity.wechatinfo.UserDemand;
import com.panda.web.entity.wechatinfo.UserMajorRgpp;
import com.panda.web.entity.wechatinfo.WechatUserinfo;
import com.panda.web.mapper.commons.PushJobMapper;
import com.panda.web.mapper.product.OpenidProductMapper;
import com.panda.web.mapper.py.CompanyMapper;
import com.panda.web.mapper.py.JobMapper;
import com.panda.web.mapper.wechat.WechatUserMapper;
import com.panda.web.mapper.wechatinfo.UserDemandMapper;
import com.panda.web.mapper.wechatinfo.UserMajorRgppMapper;
import com.panda.web.mapper.wechatinfo.WechatUserinfoMapper;
import com.panda.web.utils.pageutils.PageResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;
import java.util.function.Function;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

@Slf4j
@Component
public class JobTask {
    @Value("${gzh.api.app-id}")
    private String appId; //AppID
    @Value("${gzh.api.app_secret}")
    private String appSecret; //AppSecret

    @Autowired
    WechatUserMapper wechatUserMapper;
    @Autowired
    WechatUserinfoMapper wechatUserinfoMapper;
    @Autowired
    JobMapper jobMapper;
    @Autowired
    PushJobMapper pushJobMapper;
    @Autowired
    CompanyMapper companyMapper;
    @Autowired
    UserDemandMapper demandMapper;
    @Autowired
    CityConstants cityConstants;
    @Autowired
    OpenidProductMapper openidProductMapper;
    @Autowired
    UserMajorRgppMapper userMajorRgppMapper;
    //对接模版消息，定时推送
    // 替换为你的微信公众号的 AppID 和 AppSecret

    // 获取 access_token 的 API 地址
    private static final String ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + "wx83de228493c38c1c" + "&secret=" + "c9722f9217d91fda34f8667a56ae563b";


    //---------------------------------------------------------AAAAAAAAAAAAAAAAAAA
    @Async
    @Scheduled(cron = "0 0 8 * * ?") // 每天 8:00 执行
    public void morningTask() throws Exception {
        System.out.println("早上 8:00 执行任务，当前时间: " + new java.util.Date());
        getAssTuiSong();
    }

    @Async
    // 每天12:15执行
//    @Scheduled(cron = "0 15 12 * * ?")
    @Scheduled(cron = "0 0 12 * * ?") // 每天 12:00 执行
    public void noonTask() throws Exception {
        System.out.println("中午 12:00 执行任务，当前时间: " + new java.util.Date());
        getAssTuiSong();
    }

    @Async
    @Scheduled(cron = "0 0 18 * * ?") // 每天 18:00 执行
    public void eveningTask() throws Exception {
        getAssTuiSong();
        // 任务逻辑
    }

    //@Async
//    @Scheduled(cron = "*/10 * * * * ?")
    public void morningTaskAAA() throws Exception {
        getAssTuiSong();
        //getAAA();
    }

    //@Async
//    @Scheduled(cron = "*/10 * * * * ?")
    public void getAAA() throws Exception {
        testTuiSong();
    }

    //测试推送
    private void testTuiSong() throws Exception {

        List<Long> ids = new ArrayList<>(Arrays.asList(1259606l,
                1276437l
                ));
        for (Long id : ids) {
            Job job = jobMapper.selectById(id);
            String accessToken = getAccessToken();
            String url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + accessToken;
            //添加模版消息
            String templateIdA = "KiBr0AMi8B1sPSJjTlvUm7PiUJTFnAFnjYySDiD9UO8";
            String tzUrl = "https://zhidaole.yanbeibao2021.com/#/pages/allpage/gwDetail" + "?jid=" + 1;

            Template template = new Template();
            template.setUrl(tzUrl);
            template.setTemplate_id(templateIdA);
            template.setTouser("o9Zsy5wA0mDTND183FGdT9cEmJcU");//修改成动态/
//            template.setTouser("o9Zsy5wA0mDTND183FGdT9cEmJcU");//修改成动态/
            //推送跳转小程序  设置appid  和小程序的路径地址 //同时存在 优先小程序
            //                             template.setTouser("o9Zsy5wA0mDTND183FGdT9cEmJcU");//修改成动态
            String texttzUrlAAA = "subpack/gwDetail" + "?jid=" + job.getId();
            Miniprogram miniprogram = new Miniprogram();
            miniprogram.setAppid("wxe4ea9f874361cbc8");
            miniprogram.setPagepath(texttzUrlAAA);
            template.setMiniprogram(miniprogram);
            Plate plate = new Plate();
            Thing thing11 = new Thing();
            Thing thing15 = new Thing();
            Thing time4 = new Thing();
            Thing time16 = new Thing();
            thing15.setValue(safeProcessJobName(job.getCompanyName()));//字数长度限制
            thing11.setValue(safeProcessJobName(job.getJobName()));


            time16.setValue(formatDate(job.getStartTime()));
            if (Objects.equals(job.getEndTime(), "0")) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String startTime = job.getStartTime();
                if (!Objects.equals(startTime,"0")){
                    Date startDate = sdf.parse(startTime);
                    // 使用 Calendar 类来加上 3 个月
                    Calendar calendar = Calendar.getInstance();
                    calendar.setTime(startDate);
                    calendar.add(Calendar.MONTH, 3); // 加 3 个月
                    // 将新的时间格式化为字符串
                    String newEndTime = sdf.format(calendar.getTime());
                    time4.setValue(formatDate(newEndTime));
                }

            } else {
                time4.setValue(formatDate(job.getEndTime()));
            }

            plate.setThing11(thing11);
            plate.setThing15(thing15);
            plate.setTime4(time4);
            plate.setTime16(time16);
            template.setData(plate);

//                                 使用 Gson 转换为 JSON 字符串
            Gson gson = new Gson();
            String jsonInputString = gson.toJson(template);
            setTmplate(url, jsonInputString);
        }

    }


    public void getAssTuiSong() throws Exception {
        String accessToken = getAccessToken();
        String url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + accessToken;
        String templateIdA = "KiBr0AMi8B1sPSJjTlvUm7PiUJTFnAFnjYySDiD9UO8";
        List<WechatUser> wechatUserList = wechatUserMapper.findByOfficialOpenidStatusOb();
//        List<WechatUser> wechatUserList = new ArrayList<>();
//         先创建WechatUser对象并添加到列表中，避免IndexOutOfBoundsException
//        WechatUser testUser = new WechatUser();
//        testUser.setOpenid("oUV2r7fQ3qgKN5Zx4OLp7ky2-lhw");
//        testUser.setOfficialOpenid("o9Zsy53_8aeqLhGmqTM-xp3zqG0I");   //o9Zsy5wA0mDTND183FGdT9cEmJcU//oUV2r7ZvcGiksoN_-3EbDpz_XNzc
//        wechatUserList.add(testUser);

        if (wechatUserList != null) {
            int a = 0;
            String b = null;
            for (WechatUser user : wechatUserList) {
                String id = user.getOpenid();//唯一id
                String officialOpenid = user.getOfficialOpenid();//公众号id
                Date date1 = new Date();
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String format1 = simpleDateFormat.format(date1);
                a = a + 1;
                b = b + id + format1;
                log.info(a + "aaaaaaaaaaaaaaaaaaa        " + id);
                WechatUser wechatUser = wechatUserMapper.findByOpenId(id);
                String status = "0";
                List<Long> productIds = openidProductMapper.findByOpenidByAi(id, status);
                // 如果列表不为空，获取最大值；否则返回 0
                Long maxProductId = productIds.isEmpty() ? 0l : Collections.max(productIds);

                WechatUserinfo userinfo = wechatUserinfoMapper.findByOpenid(id);

                if (userinfo != null) {
                    if (maxProductId >= 2 || Objects.equals(wechatUser.getTrialStatus(), "1")) {   //存在套餐 大于等于2 或者 试用

                        List<UserMajorRgpp> userMajorRgppList = userMajorRgppMapper.findByOpenid(id);


                        //处理专业
                        Set<String> uniqueMajors = new HashSet<>(); // 使用Set去重

                        if (Objects.equals(userinfo.getBackground(), "本科") || Objects.equals(userinfo.getBackground(), "大专")) {
                            // 本科和大专的专业处理

                            if (userMajorRgppList != null && !userMajorRgppList.isEmpty()) {
                                for (UserMajorRgpp majorRgpp : userMajorRgppList) { //多个专业
                                    String majorName = majorRgpp.getMajorName();
                                    if (majorName != null && !majorName.trim().isEmpty()) {
                                        // 检查是否包含本科/大专的一级学科
                                        if (containsUndergraduateDiscipline(majorName)) {
                                            // 包含一级学科，需要拆分存储
                                            String[] parts = majorName.split("-");
                                            for (String part : parts) {
                                                String trimmedPart = part.trim();
                                                if (!trimmedPart.isEmpty()) {
                                                    // 去掉"类"字，但保留"自动化类"
//                                                    trimmedPart = removeClassSuffix(trimmedPart);
                                                    uniqueMajors.add(trimmedPart);
                                                }
                                            }
                                        } else {
                                            // 不包含一级学科，只存储二级及以下
                                            String[] parts = majorName.split("-");
                                            if (parts.length > 1) {
                                                // 有多个层级，去掉第一个（一级学科）
                                                for (int i = 1; i < parts.length; i++) {
                                                    String trimmedPart = parts[i].trim();
                                                    if (!trimmedPart.isEmpty()) {
                                                        // 去掉"类"字，但保留"自动化类"
//                                                        trimmedPart = removeClassSuffix(trimmedPart);
                                                        uniqueMajors.add(trimmedPart);
                                                    }
                                                }
                                            } else {
                                                // 只有一个层级，直接存储
                                                String trimmedPart = parts[0].trim();
                                                if (!trimmedPart.isEmpty()) {
                                                    // 去掉"类"字，但保留"自动化类"
//                                                    trimmedPart = removeClassSuffix(trimmedPart);
                                                    uniqueMajors.add(trimmedPart);
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        } else {
                            // 硕士的专业处理

                            if (userMajorRgppList != null && !userMajorRgppList.isEmpty()) {
                                for (UserMajorRgpp majorRgpp : userMajorRgppList) { //多个专业
                                    String majorName = majorRgpp.getMajorName();
                                    if (majorName != null && !majorName.trim().isEmpty()) {
                                        // 检查是否包含硕士的一级学科
                                        if (containsGraduateDiscipline(majorName)) {
                                            // 包含一级学科，需要拆分存储
                                            String[] parts = majorName.split("-");
                                            for (String part : parts) {
                                                String trimmedPart = part.trim();
                                                if (!trimmedPart.isEmpty()) {
                                                    // 去掉"类"字，但保留"自动化类"
                                                    trimmedPart = removeClassSuffix(trimmedPart);
                                                    uniqueMajors.add(trimmedPart);
                                                }
                                            }
                                        } else {
                                            // 不包含一级学科，只存储二级及以下
                                            String[] parts = majorName.split("-");
                                            if (parts.length > 1) {
                                                // 有多个层级，去掉第一个（一级学科）
                                                for (int i = 1; i < parts.length; i++) {
                                                    String trimmedPart = parts[i].trim();
                                                    if (!trimmedPart.isEmpty()) {
                                                        // 去掉"类"字，但保留"自动化类"
                                                        trimmedPart = removeClassSuffix(trimmedPart);
                                                        uniqueMajors.add(trimmedPart);
                                                    }
                                                }
                                            } else {
                                                // 只有一个层级，直接存储
                                                String trimmedPart = parts[0].trim();
                                                if (!trimmedPart.isEmpty()) {
                                                    // 去掉"类"字，但保留"自动化类"
                                                    trimmedPart = removeClassSuffix(trimmedPart);
                                                    uniqueMajors.add(trimmedPart);
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }

                        // 去重后转换为List
                        List<String> newMajors = new ArrayList<>(uniqueMajors);

                        String graduateTime = userinfo.getGraduateTime();
                        String currentYear = String.valueOf(LocalDate.now().getYear());  // 获取当前年份
                        String graduateYear = graduateTime.split("-")[0];
                        int month = LocalDate.now().getMonthValue();  // 获取当前年月份
                        String background = userinfo.getBackground();
                        List<String> backgroundList = getBacjground(background);//学历
                        //根据每个人的个人信息，获取进行推送数据
                        //判断年份是否相同
                        List<String> areaChList = new ArrayList<>();
                        List<UserDemand> demandList = demandMapper.findByOpenid(id);
                        if (demandList != null && !demandList.isEmpty()) {
                            UserDemand demand = demandList.get(0); // 获取第一个需求信息
                            String searchLocation = demand.getSearchLocation(); // 意向地点
                            String nativePlace = demand.getNativePlace(); // 户籍地
                            String graduateCity = demand.getGraduateCity(); // 毕业院校城市
                            areaChList = getAreaChList(searchLocation, nativePlace, graduateCity);
                        }
                        List<String> diQu = removeCitySuffix(areaChList);
                        List<Long> jobIds = new ArrayList<>();
                        Job job = new Job();
                        job.setApplyInstruction("0");
                        if (month < 7) {
                            // 7月前
                            if (Integer.parseInt(graduateYear) == Integer.parseInt(currentYear)) {
                                job.setNatureCn("校招");
                                jobIds = getXZIds(userinfo, jobIds, job, backgroundList, newMajors, diQu, graduateYear);
                            } else if (Integer.parseInt(graduateYear) > Integer.parseInt(currentYear)) {
                                job.setNatureCn("实习");
                                jobIds = getIds(userinfo, jobIds, job, backgroundList, newMajors, diQu, graduateYear);
                            } else {
                                job.setNatureCn("社招");
                                String newGraduateYear = getNewGraduateYear(graduateYear) + "届";
                                jobIds = jobMapper.selectByIdEs(job, backgroundList, newMajors, diQu, graduateYear, newGraduateYear);
                            }
                        } else {
                            // 7月及以后
                            if (Integer.parseInt(graduateYear) == Integer.parseInt(currentYear)) {
                                job.setNatureCn("社招");
                                String newGraduateYear = getNewGraduateYear(graduateYear) + "届";
                                jobIds = jobMapper.selectByIdEs(job, backgroundList, newMajors, diQu, graduateYear, newGraduateYear);
                            } else if (Integer.parseInt(graduateYear) == Integer.parseInt(currentYear) + 1) {
                                job.setNatureCn("校招");
                                jobIds = getQYHXZIds(userinfo, jobIds, job, backgroundList, newMajors, diQu, graduateYear);//7月后匹配条件
                            } else if (Integer.parseInt(graduateYear) > Integer.parseInt(currentYear) + 1) {
                                job.setNatureCn("实习");
                                jobIds = getIds(userinfo, jobIds, job, backgroundList, newMajors, diQu, graduateYear);
                            } else {
                                job.setNatureCn("社招");
                                String newGraduateYear = getNewGraduateYear(graduateYear) + "届";
                                jobIds = jobMapper.selectByIdEs(job, backgroundList, newMajors, diQu, graduateYear, newGraduateYear);
                            }
                        }
                        JobDTO dto = new JobDTO();
                        dto.setJobIds(jobIds);
                        dto.setAreaChList(diQu);

                        // 确保 dto 和 dto.getAdders() 都不为 null
                        List<String> newAdders = new ArrayList<>();
                        if (dto != null && dto.getAdders() != null && !dto.getAdders().isEmpty()) {
                            for (String addr : dto.getAdders()) {
                                // 判断 addr 是否包含 "市"
                                if (addr.contains("市")) {
                                    // 去掉 "市" 并添加到新集合
                                    addr = addr.replace("市", "");
                                }
                                newAdders.add(addr);  // 添加处理后的地址
                            }
                            dto.setAdders(newAdders);
                        }
                        if (newMajors != null && !newMajors.isEmpty()) {
                            // 检查是否包含"材料科学与工程"
                            if (newMajors.contains("材料科学与工程")) {
                                // 添加相关的材料专业
                                newMajors.add("高分子材料/高分子化学与工程");
                                newMajors.add("光电材料/光电材料与工程");
                                newMajors.add("材料类");
                                newMajors.add("复合材料");
                                newMajors.add("材料成型与加工");
                            }
                        }
                        // 获取用户已推送的岗位ID列表
                        List<Long> jobPushIds = pushJobMapper.findByOpenid(id);
                        String enterpriseStatus = userinfo.getEnterpriseStatus();
                        dto.setEnterpriseStatus(enterpriseStatus);
                        String practiceStatus = userinfo.getPracticeStatus();//是否推送实习
                        dto.setPracticeStatus(practiceStatus);
                        //是否匹配党员
                        String politicsStatus;
                        String politics = userinfo.getPolitics();
                        if (Objects.equals(politics, "其他") || Objects.equals(politics, "共青团员")) {
                            politicsStatus = "1";
                        } else {
                            politicsStatus = "0";
                        }
                        dto.setPoliticsStatus(politicsStatus);
                        dto.setUnlimitedMajor(userinfo.getUnlimitedMajor());

                        String englishFour = userinfo.getEnglishFour();
                        if (Objects.equals(englishFour,"否")){
                            dto.setEnglishFour("1");
                        }
                        String englishSix = userinfo.getEnglishSix();
                        if (Objects.equals(englishSix,"否")){
                            dto.setEnglishSix("1");
                        }

                        // 获取匹配到的所有岗位ID列表
                        List<Long> jobIdList = jobMapper.findByComTuiSong(dto);
                        // 过滤已推送的岗位，获取未推送的岗位ID列表
                        List<Long> freshJobIds = filterAndGetJobIds(jobPushIds, jobIdList);
                        // 获取未过期的已推送岗位（确保SQL正确性：end_time > NOW()）
                        Date now = new Date();
                        List<PushJob> validPushJobs = pushJobMapper.findValidPushJobsByOpenid(id, now);
                        // 获取最终推送的岗位列表（最多3个） 、//修改为5个
                        List<Job> top3Jobs = getTop3Jobs(freshJobIds, id, validPushJobs);
                        // 修改后的业务方法
                        if (top3Jobs != null && !top3Jobs.isEmpty()) {
                            for (Job top5Job : top3Jobs) {
//
                                log.info(id + "{}");
////
                                Long jobId = top5Job.getId();
                                PushJob pushJob = new PushJob();
                                Job jobAAA = jobMapper.selectById(jobId);
                                int count = pushJobMapper.findByOpenidAndJobId(id, jobId);

                                //添加模版消息
                                String tzUrl = "https://zhidaole.yanbeibao2021.com/#/pages/allpage/gwDetail" + "?jid=" + jobId;
                                Template template = new Template();
                                template.setUrl(tzUrl);
                                template.setTemplate_id(templateIdA);
                                template.setTouser(officialOpenid);//修改成动态/
//                                template.setTouser("o9Zsy5wA0mDTND183FGdT9cEmJcU");//修改成动态
                                String texttzUrlAAA = "subpack/gwDetail" + "?jid=" + jobId;
                                Miniprogram miniprogram = new Miniprogram();
                                miniprogram.setAppid("wxe4ea9f874361cbc8");
                                miniprogram.setPagepath(texttzUrlAAA);
                                template.setMiniprogram(miniprogram);
                                Plate plate = new Plate();
                                Thing thing11 = new Thing();
                                Thing thing15 = new Thing();
                                Thing time4 = new Thing();
                                Thing time16 = new Thing();
                                thing15.setValue(safeProcessJobName(top5Job.getCompanyName()));//字数长度限制
                                thing11.setValue(safeProcessJobName(top5Job.getJobName()));

                                time16.setValue(formatDate(top5Job.getStartTime()));
                                if (Objects.equals(jobAAA.getEndTime(), "0")) {
                                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                                    String startTime = jobAAA.getStartTime();
                                    if (!Objects.equals(startTime,"0")){
                                        Date startDate = sdf.parse(startTime);
                                        // 使用 Calendar 类来加上 3 个月
                                        Calendar calendar = Calendar.getInstance();
                                        calendar.setTime(startDate);
                                        calendar.add(Calendar.MONTH, 3); // 加 3 个月
                                        // 将新的时间格式化为字符串
                                        String newEndTime = sdf.format(calendar.getTime());
                                        time4.setValue(formatDate(newEndTime));
                                    }

                                } else {
                                    time4.setValue(formatDate(top5Job.getEndTime()));
                                }

                                plate.setThing11(thing11);
                                plate.setThing15(thing15);
                                plate.setTime4(time4);
                                plate.setTime16(time16);
                                template.setData(plate);
                                //使用 Gson 转换为 JSON 字符串
                                Gson gson = new Gson();
                                String jsonInputString = gson.toJson(template);
                                setTmplate(url, jsonInputString);

                                //先推送，再加入
                                if (count == 0) {
                                    Date date = new Date();
                                    String format = simpleDateFormat.format(date);
                                    pushJob.setCreateTime(date);
                                    pushJob.setCreationTime(format);
                                    if (Objects.equals(jobAAA.getEndTime(), "0")) {
                                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                                        String startTime = jobAAA.getStartTime();
                                        Date startDate = sdf.parse(startTime);
                                        // 使用 Calendar 类来加上 3 个月
                                        Calendar calendar = Calendar.getInstance();
                                        calendar.setTime(startDate);
                                        calendar.add(Calendar.MONTH, 3); // 加 3 个月
                                        // 将新的时间格式化为字符串
                                        String newEndTime = sdf.format(calendar.getTime());
                                        pushJob.setEndTime(newEndTime);
                                    } else {
                                        pushJob.setEndTime(jobAAA.getEndTime());
                                    }
                                    pushJob.setJobId(jobId);
                                    pushJob.setOpenid(id);
//                                  pushJob.setOpenid("o9Zsy5wA0mDTND183FGdT9cEmJcU");
                                    pushJobMapper.insert(pushJob);
                                }
                            }
                        }
                    }

                }
            }
            System.out.println("结束");
        }
    }

    // 新增辅助方法：安全处理岗位名称
    private String safeProcessJobName(String jobName) {
        // 1. 处理空值
        if (jobName == null || jobName.trim().isEmpty()) {
            return "未设置岗位";
        }

        // 2. 过滤非法字符（保留中文、字母、数字、空格、括号等常用符号）
        String filtered = jobName
                .replaceAll("[^\\u4e00-\\u9fa5a-zA-Z0-9（）()\\-\\s]", "") // 允许中文、字母、数字、括号、横杠、空格
                .trim();

        // 3. 截断长度（微信限制20字符）
        int maxLength = 20;
        if (filtered.length() > maxLength) {
            filtered = filtered.substring(0, maxLength);
        }

        return filtered;
    }

    public static List<String> removeCitySuffix(List<String> areaChList) {
        // 创建一个新的列表，用来存储去除"市"后的城市名称
        List<String> resultList = new ArrayList<>();

        // 遍历原始列表，去除每个城市名称中的"市"
        for (String area : areaChList) {
            // 去除 "市" 字符串
            String cityWithoutSuffix = area.replace("市", "");
            // 将处理后的城市名称添加到新的列表
            resultList.add(cityWithoutSuffix);
        }

        return resultList;
    }


    /**
     * 返回过滤后的ids
     *
     * @param userinfo
     * @param jobIds
     * @param job
     * @param backgroundList
     * @return
     */
    private List<Long> getIds(WechatUserinfo userinfo, List<Long> jobIds, Job job, List<String> backgroundList, List<String> newMajors, List<String> areaChList, String graduateYear) {

        //判断是不是海外，是
        if (Objects.equals(userinfo.getOverseasStudent(), "是") || Objects.equals(userinfo.getEnglishFour(), "是")) {

            String englishSix = "0";
            if (Objects.equals(userinfo.getEnglishSix(), "是")) {
                englishSix = "1";
            }
            String englishFour = "0";
            if (Objects.equals(userinfo.getEnglishFour(), "是")) {
                englishFour = "1";
            }

            jobIds = jobMapper.selectByIdBs(job, backgroundList, newMajors, areaChList, graduateYear, englishSix, englishFour);


        } else {
            String englishFour = "0";
            if (Objects.equals(userinfo.getEnglishFour(), "是")) {
                englishFour = "1";
            }
            String englishSix = "0";
            if (Objects.equals(userinfo.getEnglishSix(), "是")) {
                englishSix = "1";
            }
            //不满足英语4级

            jobIds = jobMapper.selectByIdBs(job, backgroundList, newMajors, areaChList, graduateYear, englishSix, englishFour);

        }
        return jobIds;
    }

    private List<Long> getXZIds(WechatUserinfo userinfo, List<Long> jobIds, Job job, List<String> backgroundList, List<String> newMajors, List<String> areaChList, String graduateYear) {

        //判断是不是海外，是
        if (Objects.equals(userinfo.getOverseasStudent(), "是") || Objects.equals(userinfo.getEnglishFour(), "是")) {

            String englishSix = "0";
            if (Objects.equals(userinfo.getEnglishSix(), "是")) {
                englishSix = "1";
            }
            String englishFour = "0";
            if (Objects.equals(userinfo.getEnglishFour(), "是")) {
                englishFour = "1";
            }
            jobIds = jobMapper.selectByIdCs(job, backgroundList, newMajors, areaChList, graduateYear, englishSix, englishFour);

        } else {
            String englishFour = "0";
            if (Objects.equals(userinfo.getEnglishFour(), "是")) {
                englishFour = "1";
            }
            String englishSix = "0";
            if (Objects.equals(userinfo.getEnglishSix(), "是")) {
                englishSix = "1";
            }
            //不满足英语4级
            jobIds = jobMapper.selectByIdCs(job, backgroundList, newMajors, areaChList, graduateYear, englishSix, englishFour);


        }
        return jobIds;
    }

    //7月后
    private List<Long> getQYHXZIds(WechatUserinfo userinfo, List<Long> jobIds, Job job, List<String> backgroundList, List<String> newMajors, List<String> areaChList, String graduateYear) {

        //判断是不是海外，是
        if (Objects.equals(userinfo.getOverseasStudent(), "是") || Objects.equals(userinfo.getEnglishFour(), "是")) {

            String englishSix = "0";
            if (Objects.equals(userinfo.getEnglishSix(), "是")) {
                englishSix = "1";
            }
            String englishFour = "0";
            if (Objects.equals(userinfo.getEnglishFour(), "是")) {
                englishFour = "1";
            }
            jobIds = jobMapper.selectByIdCCs(job, backgroundList, newMajors, areaChList, graduateYear, englishSix, englishFour);

        } else {
            String englishFour = "0";
            if (Objects.equals(userinfo.getEnglishFour(), "是")) {
                englishFour = "1";
            }
            String englishSix = "0";
            if (Objects.equals(userinfo.getEnglishSix(), "是")) {
                englishSix = "1";
            }
            //不满足英语4级
            jobIds = jobMapper.selectByIdCCs(job, backgroundList, newMajors, areaChList, graduateYear, englishSix, englishFour);


        }
        return jobIds;
    }

    // 方法：根据年月日时分秒字符串返回 "M月d日" 格式
    public static String formatDate(String inputDate) {
        // 处理空值和特殊标识
        if (inputDate == null || inputDate.isEmpty()) {
            return "";
        }

        // 新增：处理 "0" 的特殊情况
        if ("0".equals(inputDate)) {
            return "2099-01-01";
        }

        // 定义日期格式
        SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd");

        try {
            // 严格模式校验
            inputFormat.setLenient(false);
            Date date = inputFormat.parse(inputDate);
            return outputFormat.format(date);
        } catch (ParseException e) {
            // 添加异常日志（实际生产环境应使用日志框架）
            System.err.println("日期解析失败 | 输入值: " + inputDate + " | 错误: " + e.getMessage());
            return null;  // 保持原逻辑返回null
        }
    }

    public List<Long> filterAndGetJobIds(List<Long> jobPushId, List<Long> jobIdList) {
        // 过滤掉已推送过的岗位ID，并且保证不打乱顺序
        List<Long> filteredJobIds = jobIdList.stream()
                .filter(jobId -> !jobPushId.contains(jobId))  // 过滤掉已推送过的岗位ID
                .limit(4)  // 取出前3个
                .collect(Collectors.toList());

        // 如果岗位不足3个，不进行推送
//        return filteredJobIds.size() == 3 ? filteredJobIds : List.of();
        return filteredJobIds;
    }

    public List<Job> getTop3Jobs(//更新为5个.
                                 List<Long> freshJobIds,
                                 String openid,
                                 List<PushJob> validPushJobs) {

        List<Job> result = new ArrayList<>(4);

        // 1. 处理新岗位（使用分页查询优化）
        if (!CollectionUtils.isEmpty(freshJobIds)) {
            JobDTO queryDTO = new JobDTO();
            queryDTO.setJobIds(freshJobIds);
            queryDTO.setPageSize(4);
            List<Job> freshJobs = jobMapper.findByPushDom(queryDTO);
            result.addAll(freshJobs);
            log.info("新增岗位数: {}", freshJobs.size());
        }

        // 2. 如果已满足数量直接返回
        if (result.size() >= 4) {
            return result.subList(0, 4);
        }

        // 3. 计算需要补充的数量
        int needed = 4 - result.size();
        log.info("需要补充数量: {}", needed);

        // 4. 智能补充逻辑优化
        // 4. 智能补充逻辑优化
        if (needed > 0 && !CollectionUtils.isEmpty(validPushJobs)) {
            // 安全排序：先按selectedCount升序，null值视为0；再按createTime降序
            List<PushJob> sortedPushJobs = validPushJobs.stream()
                    .filter(pushJob -> pushJob != null && pushJob.getJobId() != null)
                    .sorted(Comparator.comparing(
                                            (PushJob p) -> p.getSelectedCount() != null ? p.getSelectedCount() : 0)
                                    .thenComparing(
                                            (PushJob p) -> p.getCreateTime() != null ? p.getCreateTime() : new Date(0)
//                                    Comparator.reverseOrder()  // 关键修复：恢复倒序排序
                                    )
                    )
                    .collect(Collectors.toList());

            // 获取需要补充的jobIds（取前N个）
            List<Long> candidateIds = sortedPushJobs.stream()
                    .map(PushJob::getJobId)
                    .limit(needed)
                    .collect(Collectors.toList());

            log.info("候选补充ID: {}", candidateIds);

            if (!CollectionUtils.isEmpty(candidateIds)) {
                // 批量查询（需要确保SQL查询保留原始顺序）
                JobDTO queryDTO = new JobDTO();
                queryDTO.setJobIds(candidateIds);
                queryDTO.setPageSize(needed);// 添加保持ID顺序参数（需在SQL实现）
                List<Job> supplementJobs = jobMapper.findByPushDom(queryDTO);
                result.addAll(supplementJobs);
                log.info("实际补充数: {}", supplementJobs.size());

                // 更新selectedCount（需要事务支持）
                pushJobMapper.batchUpdateSelectionStatus(candidateIds, openid);
            }

        }

        return result.stream().limit(4).collect(Collectors.toList());
    }


    public List<String> getAreaChList(String searchLocation, String nativePlace, String graduateCity) {
        // 使用LinkedHashSet去重并保持顺序
        Set<String> areaSet = new LinkedHashSet<>();

        // 将用户选择的意向地点分别加入集合
        for (String loc : searchLocation.split(",")) {
            String ssss = extractCity(loc.trim());
            areaSet.add(ssss);
        }

        // 新一线城市
        List<String> cyx = new ArrayList<>(Arrays.asList("北京", "上海", "广州", "深圳", "杭州"));
//        List<String> xyx = new ArrayList<>(Arrays.asList("成都", "重庆", "杭州", "武汉",
//                "苏州", "西安", "南京", "长沙",
//                "天津", "郑州", "东莞", "青岛",
//                "昆明", "宁波", "合肥", "全国"));

        areaSet.addAll(cyx);
//        areaSet.addAll(xyx);

//        // 将用户选择的地点分别加入集合
//        for (String loc : nativePlace.split(",")) {
//            areaSet.add(loc.trim());
//        }
//        for (String loc : graduateCity.split(",")) {
//            areaSet.add(loc.trim());
//        }

        // 将Set转换为List并返回

        return new ArrayList<>(areaSet);
    }

    private static String extractCity(String areaCn) {
        if (areaCn.endsWith("市")) {
            return areaCn.substring(0, areaCn.length() - 1);  // 去掉"市"字
        }
        return areaCn;  // 如果没有"市"字，直接返回
    }


    /**
     * 从户籍地中提取省份
     *
     * @param nativePlace 户籍地（如：北京市北京市）
     * @return 省份（如：北京）
     */
    private String getProvinceFromNativePlace(String nativePlace) {
        if (nativePlace == null || nativePlace.isEmpty()) {
            return null;
        }
        // 假设户籍地格式为 "省份+城市"，如 "北京市北京市"
        return nativePlace.substring(0, 2); // 提取前两个字作为省份
    }


    private static String extractAgeRequirement(String contents) {
        // 正则表达式匹配放宽条件（如 "放宽至40岁以下"）
        Pattern relaxedPattern = Pattern.compile("放宽至(\\d+)岁以下");
        Matcher relaxedMatcher = relaxedPattern.matcher(contents);
        if (relaxedMatcher.find()) {
            return relaxedMatcher.group(1); // 返回放宽条件的年龄
        }

        // 正则表达式匹配原始年龄要求（如 "35周岁以下"）
        Pattern originalPattern = Pattern.compile("(?:年龄)?(\\d+)\\s*周岁以下");
        Matcher originalMatcher = originalPattern.matcher(contents);
        if (originalMatcher.find()) {
            return originalMatcher.group(1); // 返回原始年龄要求
        }

        return null; // 没有匹配到年龄要求
    }

    private List<String> getBacjground(String background) {

        List<String> backgroundList = new ArrayList<>();  //学历
        if (Objects.equals(background, "大专")) {
            backgroundList.add("大专");
            backgroundList.add("专科及以上");
        } else if (Objects.equals(background, "硕士")) {
            backgroundList.add("硕士");
            backgroundList.add("硕士及以上");
            backgroundList.add("本科");
            backgroundList.add("本科及以上");
        } else if (Objects.equals(background, "博士")) {
            backgroundList.add("博士");
            backgroundList.add("硕士");
            backgroundList.add("硕士及以上");
            backgroundList.add("博士及以上");
        } else if (Objects.equals(background, "本科")) {
            backgroundList.add("本科");
            backgroundList.add("本科及以上");
            backgroundList.add("大专");
            backgroundList.add("专科及以上");
        } else {
            backgroundList.add("大专");
            backgroundList.add("中专");
            backgroundList.add("中技");
            backgroundList.add("初中");
            backgroundList.add("高中");
            backgroundList.add("初中及以下");
        }
        return backgroundList;
    }

    public static void main(String[] args) {
        try {
            // 调用方法获取 access_token
            String accessToken = getAccessToken();  //获取的微信公众号的access_token
            String url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + accessToken;
            String templateIdA = "KiBr0AMi8B1sPSJjTlvUm7PiUJTFnAFnjYySDiD9UO8";
            String templateIdB = "KiBr0AMi8B1sPSJjTlvUm_VsgaNzXCoBMm3iecd78yg";
            String tzUrl = "https://zhidaole.yanbeibao2021.com/#/pages/index/index";


            //添加模版消息
            Template template = new Template();
            template.setUrl(tzUrl);
            template.setTemplate_id(templateIdA);
            template.setTouser("o9Zsy5_P8hzQtPUoxCNvLuwdGjzI");
            Plate plate = new Plate();
            Thing thing11 = new Thing();
            Thing thing15 = new Thing();
            Thing time4 = new Thing();
            Thing time16 = new Thing();

            thing11.setValue("AAAAAAA\nBBBBBB");
            thing15.setValue("CCCCC\nDDDDD");
            time16.setValue("2025-03-07 12:00:00");
            time4.setValue("2025-03-07 18:00:00");
            plate.setThing11(thing11);
            plate.setThing15(thing15);
            plate.setTime4(time4);
            plate.setTime16(time16);
            template.setData(plate);

// 使用 Gson 转换为 JSON 字符串
            Gson gson = new Gson();
            String jsonInputString = gson.toJson(template);
//            String jsonInputString = "{"
//                    + "\"touser\": \"o9Zsy51Cedmv9DBC98e8q21ssVaw\","
//                    + "\"template_id\": \"" + templateIdA + "\","
//                    + "\"url\": \"\","
//                    + "\"data\": {"
//                    + "\"thing15\": {\"value\": \"DDDDDDDDDDDDD\"},"  // 确保提供 thing15 的值
//                    + "\"thing11\": {\"value\": \"CCCCCCCCCCCC\"},"
//                    + "\"time16\": {\"value\": \"2025-03-07 12:00:00\"},"
//                    + "\"time4\": {\"value\": \"2025-03-07 18:00:00\"}"
//                    + "}"
//                    + "}";

            setTmplate(url, jsonInputString);//模版发送消息
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }


    //发送模版消息
    private static void setTmplate(String url, String jsonInputString) throws IOException {
        HttpURLConnection con = (HttpURLConnection) new URL(url).openConnection();
        con.setRequestMethod("POST");
        con.setRequestProperty("Content-Type", "application/json; utf-8");
        con.setRequestProperty("Accept", "application/json");
        con.setDoOutput(true);

        try (OutputStream os = con.getOutputStream()) {
            byte[] input = jsonInputString.getBytes(StandardCharsets.UTF_8);
            os.write(input, 0, input.length);
        }

        int responseCode = con.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) {
            // 读取响应
            try (java.util.Scanner scanner = new java.util.Scanner(con.getInputStream(), StandardCharsets.UTF_8.name())) {
                String response = scanner.useDelimiter("\\A").next();
                System.out.println(response);
            }
        } else {
            System.out.println("请求失败，响应码: " + responseCode);
        }
    }


    /**
     * 获取微信 access_token
     *
     * @return access_token
     * @throws Exception 如果请求失败或解析出错
     */
    public static String getAccessToken() throws Exception {
        URL url = new URL(ACCESS_TOKEN_URL);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");

        int responseCode = connection.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) {
            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            StringBuilder response = new StringBuilder();
            String inputLine;

            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();

            // 使用 Gson 解析 JSON
            JsonParser parser = new JsonParser();
            JsonObject jsonObject = parser.parse(response.toString()).getAsJsonObject();

            // 检查是否有 access_token 字段
            if (jsonObject.has("access_token")) {
                return jsonObject.get("access_token").getAsString();
            } else {
                // 如果返回错误信息，打印错误码和错误信息
                if (jsonObject.has("errcode")) {
                    int errcode = jsonObject.get("errcode").getAsInt();
                    String errmsg = jsonObject.get("errmsg").getAsString();
                    throw new Exception("微信返回错误: errcode=" + errcode + ", errmsg=" + errmsg);
                } else {
                    throw new Exception("微信返回的数据格式不正确: " + response.toString());
                }
            }
        } else {
            throw new Exception("Failed to get access token. Response code: " + responseCode);
        }
    }

    /**
     * 截取前两位
     *
     * @param graduateYear
     * @return
     */
    private String getNewGraduateYear(String graduateYear) {
        if (graduateYear == null || !graduateYear.matches("\\d+")) {
            return null;
        }
        // 取最后两位（长度不足时直接返回整个字符串）
        int startIndex = Math.max(0, graduateYear.length() - 2);
        return graduateYear.substring(startIndex);
    }

    /**
     * 检查专业是否包含本科/大专的一级学科
     * 本科/大专的一级学科：哲学，经济学，教育学，文学，历史学，管理学，艺术学
     */
    private boolean containsUndergraduateDiscipline(String majorName) {
        if (majorName == null) return false;

        String[] undergraduateDisciplines = {
                "哲学", "经济学", "教育学", "文学", "历史学", "管理学", "艺术学"
        };

        for (String discipline : undergraduateDisciplines) {
            if (majorName.contains(discipline)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 检查专业是否包含硕士的一级学科
     * 硕士的一级学科：哲学，经济学，教育学，文学，历史学，管理学，军事学，艺术学
     */
    private boolean containsGraduateDiscipline(String majorName) {
        if (majorName == null) return false;

        String[] graduateDisciplines = {
                "哲学", "经济学", "教育学", "文学", "历史学", "管理学", "军事学", "艺术学"
        };

        for (String discipline : graduateDisciplines) {
            if (majorName.contains(discipline)) {
                return true;
            }
        }
        return false;
    }

    private String removeClassSuffix(String majorName) {
        // 去掉"类"字，但保留"自动化类"
        if ("自动化类".equals(majorName)) {
            return majorName; // 保留"自动化类"
        }
        return majorName.replace("类", "");
    }
    //新推送处理
    public void getNewAssTuiSong() throws Exception {
        String accessToken = getAccessToken();
        String url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + accessToken;
        String templateIdA = "KiBr0AMi8B1sPSJjTlvUm7PiUJTFnAFnjYySDiD9UO8";
        List<WechatUser> wechatUserList = wechatUserMapper.findByOfficialOpenidStatusOb();
        if (wechatUserList != null) {

            for (WechatUser user : wechatUserList) {
                String id = user.getOpenid();//唯一id
                String officialOpenid = user.getOfficialOpenid();//公众号id
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                WechatUser wechatUser = wechatUserMapper.findByOpenId(id);
                String status = "0";
                List<Long> productIds = openidProductMapper.findByOpenidByAi(id, status);
                // 如果列表不为空，获取最大值；否则返回 0
                Long maxProductId = productIds.isEmpty() ? 0l : Collections.max(productIds);

                WechatUserinfo userinfo = wechatUserinfoMapper.findByOpenid(id);

                if (userinfo != null) {
                    if (maxProductId >= 2 || Objects.equals(wechatUser.getTrialStatus(), "1")) {   //存在套餐 大于等于2 或者 试用

                        List<UserMajorRgpp> userMajorRgppList = userMajorRgppMapper.findByOpenid(id);


                        //处理专业
                        Set<String> uniqueMajors = new HashSet<>(); // 使用Set去重

                        if (Objects.equals(userinfo.getBackground(), "本科") || Objects.equals(userinfo.getBackground(), "大专")) {
                            // 本科和大专的专业处理

                            if (userMajorRgppList != null && !userMajorRgppList.isEmpty()) {
                                for (UserMajorRgpp majorRgpp : userMajorRgppList) { //多个专业
                                    String majorName = majorRgpp.getMajorName();
                                    if (majorName != null && !majorName.trim().isEmpty()) {
                                        // 检查是否包含本科/大专的一级学科
                                        if (containsUndergraduateDiscipline(majorName)) {
                                            // 包含一级学科，需要拆分存储
                                            String[] parts = majorName.split("-");
                                            for (String part : parts) {
                                                String trimmedPart = part.trim();
                                                if (!trimmedPart.isEmpty()) {
                                                    // 去掉"类"字，但保留"自动化类"
//                                                    trimmedPart = removeClassSuffix(trimmedPart);
                                                    uniqueMajors.add(trimmedPart);
                                                }
                                            }
                                        } else {
                                            // 不包含一级学科，只存储二级及以下
                                            String[] parts = majorName.split("-");
                                            if (parts.length > 1) {
                                                // 有多个层级，去掉第一个（一级学科）
                                                for (int i = 1; i < parts.length; i++) {
                                                    String trimmedPart = parts[i].trim();
                                                    if (!trimmedPart.isEmpty()) {
                                                        // 去掉"类"字，但保留"自动化类"
//                                                        trimmedPart = removeClassSuffix(trimmedPart);
                                                        uniqueMajors.add(trimmedPart);
                                                    }
                                                }
                                            } else {
                                                // 只有一个层级，直接存储
                                                String trimmedPart = parts[0].trim();
                                                if (!trimmedPart.isEmpty()) {
                                                    // 去掉"类"字，但保留"自动化类"
//                                                    trimmedPart = removeClassSuffix(trimmedPart);
                                                    uniqueMajors.add(trimmedPart);
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        } else {
                            // 硕士的专业处理

                            if (userMajorRgppList != null && !userMajorRgppList.isEmpty()) {
                                for (UserMajorRgpp majorRgpp : userMajorRgppList) { //多个专业
                                    String majorName = majorRgpp.getMajorName();
                                    if (majorName != null && !majorName.trim().isEmpty()) {
                                        // 检查是否包含硕士的一级学科
                                        if (containsGraduateDiscipline(majorName)) {
                                            // 包含一级学科，需要拆分存储
                                            String[] parts = majorName.split("-");
                                            for (String part : parts) {
                                                String trimmedPart = part.trim();
                                                if (!trimmedPart.isEmpty()) {
                                                    // 去掉"类"字，但保留"自动化类"
//                                                    trimmedPart = removeClassSuffix(trimmedPart);
                                                    uniqueMajors.add(trimmedPart);
                                                }
                                            }
                                        } else {
                                            // 不包含一级学科，只存储二级及以下
                                            String[] parts = majorName.split("-");
                                            if (parts.length > 1) {
                                                // 有多个层级，去掉第一个（一级学科）
                                                for (int i = 1; i < parts.length; i++) {
                                                    String trimmedPart = parts[i].trim();
                                                    if (!trimmedPart.isEmpty()) {
                                                        // 去掉"类"字，但保留"自动化类"
//                                                        trimmedPart = removeClassSuffix(trimmedPart);
                                                        uniqueMajors.add(trimmedPart);
                                                    }
                                                }
                                            } else {
                                                // 只有一个层级，直接存储
                                                String trimmedPart = parts[0].trim();
                                                if (!trimmedPart.isEmpty()) {
                                                    // 去掉"类"字，但保留"自动化类"
//                                                    trimmedPart = removeClassSuffix(trimmedPart);
                                                    uniqueMajors.add(trimmedPart);
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }

                        // 去重后转换为List
                        List<String> newMajors = new ArrayList<>(uniqueMajors);

                        String graduateTime = userinfo.getGraduateTime();
                        String currentYear = String.valueOf(LocalDate.now().getYear());  // 获取当前年份
                        String graduateYear = graduateTime.split("-")[0];
                        int month = LocalDate.now().getMonthValue();  // 获取当前年月份
                        String background = userinfo.getBackground();
                        List<String> backgroundList = getBacjground(background);//学历
                        //根据每个人的个人信息，获取进行推送数据
                        //判断年份是否相同
                        List<String> areaChList = new ArrayList<>();
                        List<UserDemand> demandList = demandMapper.findByOpenid(id);
                        if (demandList != null && !demandList.isEmpty()) {
                            UserDemand demand = demandList.get(0); // 获取第一个需求信息
                            String searchLocation = demand.getSearchLocation(); // 意向地点
                            String nativePlace = demand.getNativePlace(); // 户籍地
                            String graduateCity = demand.getGraduateCity(); // 毕业院校城市
                            areaChList = getAreaChList(searchLocation, nativePlace, graduateCity);
                        }
                        List<String> diQu = removeCitySuffix(areaChList);
                        List<Long> jobIds = new ArrayList<>();
                        Job job = new Job();
                        job.setApplyInstruction("0");
                        if (month < 7) {
                            // 7月前
                            if (Integer.parseInt(graduateYear) == Integer.parseInt(currentYear)) {
                                job.setNatureCn("校招");
                                jobIds = getXZIds(userinfo, jobIds, job, backgroundList, newMajors, diQu, graduateYear);
                            } else if (Integer.parseInt(graduateYear) > Integer.parseInt(currentYear)) {
                                job.setNatureCn("实习");
                                jobIds = getIds(userinfo, jobIds, job, backgroundList, newMajors, diQu, graduateYear);
                            } else {
                                job.setNatureCn("社招");
                                String newGraduateYear = getNewGraduateYear(graduateYear) + "届";
                                jobIds = jobMapper.selectByIdEs(job, backgroundList, newMajors, diQu, graduateYear, newGraduateYear);
                            }
                        } else {
                            // 7月及以后
                            if (Integer.parseInt(graduateYear) == Integer.parseInt(currentYear)) {
                                job.setNatureCn("社招");
                                String newGraduateYear = getNewGraduateYear(graduateYear) + "届";
                                jobIds = jobMapper.selectByIdEs(job, backgroundList, newMajors, diQu, graduateYear, newGraduateYear);
                            } else if (Integer.parseInt(graduateYear) == Integer.parseInt(currentYear) + 1) {
                                job.setNatureCn("校招");
                                jobIds = getQYHXZIds(userinfo, jobIds, job, backgroundList, newMajors, diQu, graduateYear);//7月后匹配条件
                            } else if (Integer.parseInt(graduateYear) > Integer.parseInt(currentYear) + 1) {
                                job.setNatureCn("实习");
                                jobIds = getIds(userinfo, jobIds, job, backgroundList, newMajors, diQu, graduateYear);
                            } else {
                                job.setNatureCn("社招");
                                String newGraduateYear = getNewGraduateYear(graduateYear) + "届";
                                jobIds = jobMapper.selectByIdEs(job, backgroundList, newMajors, diQu, graduateYear, newGraduateYear);
                            }
                        }
                        JobDTO dto = new JobDTO();
                        dto.setJobIds(jobIds);
                        dto.setAreaChList(diQu);

                        // 确保 dto 和 dto.getAdders() 都不为 null
                        List<String> newAdders = new ArrayList<>();
                        if (dto != null && dto.getAdders() != null && !dto.getAdders().isEmpty()) {
                            for (String addr : dto.getAdders()) {
                                // 判断 addr 是否包含 "市"
                                if (addr.contains("市")) {
                                    // 去掉 "市" 并添加到新集合
                                    addr = addr.replace("市", "");
                                }
                                newAdders.add(addr);  // 添加处理后的地址
                            }
                            dto.setAdders(newAdders);
                        }
                        if (newMajors != null && !newMajors.isEmpty()) {
                            // 检查是否包含"材料科学与工程"
                            if (newMajors.contains("材料科学与工程")) {
                                // 添加相关的材料专业
                                newMajors.add("高分子材料/高分子化学与工程");
                                newMajors.add("光电材料/光电材料与工程");
                                newMajors.add("材料类");
                                newMajors.add("复合材料");
                                newMajors.add("材料成型与加工");
                            }
                        }
                        // 获取用户已推送的岗位ID列表
                        List<Long> jobPushIds = pushJobMapper.findByOpenid(id);
                        String enterpriseStatus = userinfo.getEnterpriseStatus();
                        dto.setEnterpriseStatus(enterpriseStatus);
                        String practiceStatus = userinfo.getPracticeStatus();//是否推送实习
                        dto.setPracticeStatus(practiceStatus);
                        //是否匹配党员
                        String politicsStatus;
                        String politics = userinfo.getPolitics();
                        if (Objects.equals(politics, "其他") || Objects.equals(politics, "共青团员")) {
                            politicsStatus = "1";
                        } else {
                            politicsStatus = "0";
                        }
                        dto.setPoliticsStatus(politicsStatus);
                        dto.setUnlimitedMajor(userinfo.getUnlimitedMajor());
                        // 获取匹配到的所有岗位ID列表
                        List<Long> jobIdList = jobMapper.findByComTuiSong(dto);
                        // 过滤已推送的岗位，获取未推送的岗位ID列表
                        List<Long> freshJobIds = filterAndGetJobIds(jobPushIds, jobIdList);
                        // 获取未过期的已推送岗位（确保SQL正确性：end_time > NOW()）
                        Date now = new Date();
                        List<PushJob> validPushJobs = pushJobMapper.findValidPushJobsByOpenid(id, now);
                        // 获取最终推送的岗位列表（最多3个） 、//修改为5个
                        List<Job> top3Jobs = getTop3Jobs(freshJobIds, id, validPushJobs);
                        // 修改后的业务方法
                        if (top3Jobs != null && !top3Jobs.isEmpty()) {
                            for (Job top5Job : top3Jobs) {
//
                                log.info(id + "{}");
//
                                Long jobId = top5Job.getId();
                                PushJob pushJob = new PushJob();
                                Job jobAAA = jobMapper.selectById(jobId);
                                int count = pushJobMapper.findByOpenidAndJobId(id, jobId);

                                //添加模版消息
                                String tzUrl = "https://zhidaole.yanbeibao2021.com/#/pages/allpage/gwDetail" + "?jid=" + jobId;
                                Template template = new Template();
                                template.setUrl(tzUrl);
                                template.setTemplate_id(templateIdA);
                                template.setTouser(officialOpenid);//修改成动态/
//                                template.setTouser("o9Zsy5wA0mDTND183FGdT9cEmJcU");//修改成动态
                                String texttzUrlAAA = "subpack/gwDetail" + "?jid=" + jobId;
                                Miniprogram miniprogram = new Miniprogram();
                                miniprogram.setAppid("wxe4ea9f874361cbc8");
                                miniprogram.setPagepath(texttzUrlAAA);
                                template.setMiniprogram(miniprogram);
                                Plate plate = new Plate();
                                Thing thing11 = new Thing();
                                Thing thing15 = new Thing();
                                Thing time4 = new Thing();
                                Thing time16 = new Thing();
                                thing15.setValue(safeProcessJobName(top5Job.getCompanyName()));//字数长度限制
                                thing11.setValue(safeProcessJobName(top5Job.getJobName()));

                                time16.setValue(formatDate(top5Job.getStartTime()));
                                if (Objects.equals(jobAAA.getEndTime(), "0")) {
                                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                                    String startTime = jobAAA.getStartTime();
                                    if (!Objects.equals(startTime,"0")){
                                        Date startDate = sdf.parse(startTime);
                                        // 使用 Calendar 类来加上 3 个月
                                        Calendar calendar = Calendar.getInstance();
                                        calendar.setTime(startDate);
                                        calendar.add(Calendar.MONTH, 3); // 加 3 个月
                                        // 将新的时间格式化为字符串
                                        String newEndTime = sdf.format(calendar.getTime());
                                        time4.setValue(formatDate(newEndTime));
                                    }

                                } else {
                                    time4.setValue(formatDate(top5Job.getEndTime()));
                                }

                                plate.setThing11(thing11);
                                plate.setThing15(thing15);
                                plate.setTime4(time4);
                                plate.setTime16(time16);
                                template.setData(plate);
                                //使用 Gson 转换为 JSON 字符串
                                Gson gson = new Gson();
                                String jsonInputString = gson.toJson(template);
                                setTmplate(url, jsonInputString);

                                //先推送，再加入
                                if (count == 0) {
                                    Date date = new Date();
                                    String format = simpleDateFormat.format(date);
                                    pushJob.setCreateTime(date);
                                    pushJob.setCreationTime(format);
                                    if (Objects.equals(jobAAA.getEndTime(), "0")) {
                                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                                        String startTime = jobAAA.getStartTime();
                                        Date startDate = sdf.parse(startTime);
                                        // 使用 Calendar 类来加上 3 个月
                                        Calendar calendar = Calendar.getInstance();
                                        calendar.setTime(startDate);
                                        calendar.add(Calendar.MONTH, 3); // 加 3 个月
                                        // 将新的时间格式化为字符串
                                        String newEndTime = sdf.format(calendar.getTime());
                                        pushJob.setEndTime(newEndTime);
                                    } else {
                                        pushJob.setEndTime(jobAAA.getEndTime());
                                    }
                                    pushJob.setJobId(jobId);
                                    pushJob.setOpenid(id);
//                                  pushJob.setOpenid("o9Zsy5wA0mDTND183FGdT9cEmJcU");
                                    pushJobMapper.insert(pushJob);
                                }
                            }
                        }
                    }

                }
            }
            System.out.println("结束");
        }



    }
}
